package com.youlu.campus.web.config.filter;

import com.youlu.campus.entity.UserPO;
import com.youlu.campus.service.visitor.UserBlackListService;
import com.youlu.campus.web.common.base.RequestContext;
import com.youlu.campus.web.config.filter.utils.ResponseUtils;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 用户黑名单限制 过滤器
 *
 * @Description: IpBlackListFilter
 * @Date 2025/7/10
 * @module UserLimitFilter
 * @author: su
 */
@Slf4j
public class UserLimitFilter extends OncePerRequestFilter {

    private UserBlackListService userBlackListService;

    public UserLimitFilter(UserBlackListService userBlackListService) {
        this.userBlackListService = userBlackListService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        UserPO curUser = RequestContext.getCurUser();
        if (Objects.isNull(curUser)) {
            filterChain.doFilter(request, response);
            return;
        }
        boolean exist = userBlackListService.exist(curUser.getId());
        if (exist) {
            log.error("用户在黑名单中 userId:{}", curUser.getId());
            ResponseUtils.writeOutJson(response, QResult.fail(111, "HMD服务器繁忙,,请24小时后重试"));
            return;
        }
        //放行
        filterChain.doFilter(request, response);
    }

}
